package com.tz.controller;

import com.tz.entity.User;
import com.tz.mapper.UserMapper;
import com.tz.service.UserService;
import com.tz.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //查询数据库中否有用户
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //f
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

        //2.2获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //2.3获取Mapper
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user1 = userMapper.selectByUsername(username);
//        User user1 = userService.register(username);


        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        //数据库中没有该用户创建该用户
        if (user1 == null){
            userMapper.add(user);
            sqlSession.commit();
//            writer.write("success!!!");

            String contextPath = request.getContextPath();
            //注册成功跳转登陆页面
            response.sendRedirect(contextPath+"/login.jsp");
        }else {
            writer.write("user is exit!!!");
        }
        sqlSession.close();

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
